package cn.crawler.app.web.modules.controllers.open.file;

import cn.hutool.core.lang.UUID;
import cn.crawler.app.sys.modules.services.SysParamService;
import cn.crawler.app.web.commons.base.Globals;
import cn.crawler.app.web.commons.utils.DateUtil;
import cn.crawler.framework.base.model.enums.BizExceptionEnum;
import cn.crawler.framework.util.Result;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.nutz.boot.starter.ftp.FtpService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.random.R;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.impl.AdaptorErrorContext;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;

/**
 * Created by Wizzer on 2016/7/5.
 */
@IocBean
@At("/open/file/upload")
public class UploadController {
    private static final Log log = Logs.get();
    @Inject
    private FtpService ftpService;
    @Inject("java:$conf.get('cms.video.url')")
    private String videoUrl;
    @Inject
    @Reference
    private SysParamService sysParamService;

    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:fileUpload"})
    @At
    @Ok("json")
    @RequiresAuthentication
    //AdaptorErrorContext必须是最后一个参数
    public Object file(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
        try {
            if (err != null && err.getAdaptorErr() != null) {
                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
            } else if (tf == null) {
                return Result.error(BizExceptionEnum.EMPTY_FILE);
            } else {
                String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
                String filePath = Globals.AppUploadBase + "/file/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
                String fileName = R.UU32() + suffixName;
                String url = filePath + fileName;
                if (ftpService.upload(filePath, fileName, tf.getInputStream())) {
                    return Result.success(BizExceptionEnum.UPLOAD_SUCCESS, NutMap.NEW().addv("file_type", suffixName).addv("file_name", tf.getSubmittedFileName()).addv("file_size", tf.getSize()).addv("file_url", url));
                } else {
                    return Result.error(BizExceptionEnum.UPLOAD_FAIL);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return Result.error(BizExceptionEnum.FILE_FORMAT_INCORRECT);
        }
    }

    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:videoUpload"})
    @At
    @Ok("json")
    @RequiresAuthentication
    //AdaptorErrorContext必须是最后一个参数
    public Object video(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
        try {
            if (err != null && err.getAdaptorErr() != null) {
                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
            } else if (tf == null) {
                return Result.error(BizExceptionEnum.EMPTY_FILE);
            } else {
                String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
                String filePath = Globals.AppUploadBase + "/video/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
                String fileName = R.UU32() + suffixName;
                String url = filePath + fileName;
                if (ftpService.upload(filePath, fileName, tf.getInputStream())) {
                    return Result.success(BizExceptionEnum.UPLOAD_SUCCESS, NutMap.NEW().addv("file_type", suffixName).addv("file_name", tf.getSubmittedFileName()).addv("file_size", tf.getSize()).addv("file_url", url));
                } else {
                    return Result.error(BizExceptionEnum.UPLOAD_FAIL);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return Result.error(BizExceptionEnum.FILE_FORMAT_INCORRECT);
        }
    }

    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:imageUpload"})
    @At
    @Ok("json")
//    @RequiresAuthentication
    //AdaptorErrorContext必须是最后一个参数
    public Object image(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
        try {
            if (err != null && err.getAdaptorErr() != null) {
                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
            } else if (tf == null) {
                return Result.error(BizExceptionEnum.EMPTY_FILE);
            } else {

                File f = tf.getFile();
                String fileName = f.getName();
                String fileTyle = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                fileName = R.UU32() + fileTyle;
                String toPath = Globals.AppUploadBase + "/" + fileName;
                // 移动文件
                f.renameTo(new File(toPath));
                //文件上传成功,修改数据库
                NutMap resmap = new NutMap();
                resmap.addv("picture", fileName);
                return Result.success(BizExceptionEnum.UPLOAD_SUCCESS, resmap);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return Result.error(BizExceptionEnum.PICTURE_FORMAT_INCORRECT);
        }
    }

    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:imageUpload"})
    @At
    @Ok("json")
    @RequiresAuthentication
    //AdaptorErrorContext必须是最后一个参数
    public Object image2(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
        try {
            if (err != null && err.getAdaptorErr() != null) {
                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
            } else if (tf == null) {
                return Result.error(BizExceptionEnum.EMPTY_FILE);
            } else {
                String uri = "/image/" + DateUtil.format(new Date(), "yyyyMMdd") + "/" + R.UU32() + tf.getSubmittedFileName().substring(tf.getSubmittedFileName().indexOf("."));
                String f = Globals.AppUploadBase + uri;
                Files.write(new File(f), tf.getInputStream());
                return Result.success(BizExceptionEnum.UPLOAD_SUCCESS, uri);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        } catch (Throwable e) {
            return Result.error(BizExceptionEnum.PICTURE_FORMAT_INCORRECT);
        }
    }


    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:apkUpload"})
    @At
    @Ok("json")
    @RequiresAuthentication
    //AdaptorErrorContext必须是最后一个参数
    public Object apkFile(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
        try {
            if (err != null && err.getAdaptorErr() != null) {
                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
            } else if (tf == null) {
                return Result.error(BizExceptionEnum.EMPTY_FILE);
            } else {
//                SysParam sysParam = sysParamService.fetch();
//                String ftpHost = sysParam.getFtpHost();
//                Integer ftpPort = sysParam.getFtpPort();
//                FtpUtil ftpUtil = new FtpUtil(ftpHost, ftpPort, sysParam.getFtpUserName(), sysParam.getFtpPassword());
                //ftp连接登录
//                ftpUtil.login();
                //上传文件
//                File file = tf.getFile();
                //文件名
//                String fileName = tf.getSubmittedFileName();
                //上传路径
//                String ftpUploadPath = sysParam.getFtpUploadPath();
//                String filePath = ftpHost;
//                if(ftpPort > 0){
//                    filePath = filePath + ":" + sysParam.getFtpPort();
//                }
//                filePath = filePath + ftpUploadPath + fileName;
//                boolean result = ftpUtil.uploadFile(file, ftpUploadPath, fileName);
//                if(!result){
//                    return Result.error();
//                }
                //登出
//                ftpUtil.logOut();
//                return Result.success(BizExceptionEnum.UPLOAD_SUCCESS,
//                        Result.createMap("fileName", fileName,
//                                "fileUploadPath", sysParam.getFtpUploadPath(),
//                                "filePath", filePath));
                File file = tf.getFile();
                String suffixName = file.getName().substring(file.getName().indexOf(".") + 1);
                String fileName = UUID.fastUUID() + "." + suffixName;
                String fileUri = "/" + suffixName + "/" + fileName;
                String filePath = Globals.AppUploadBase + fileUri;
                File toWrite = new File(filePath);
                Files.write(toWrite, tf.getInputStream());
                return Result.success(BizExceptionEnum.UPLOAD_SUCCESS,
                        Result.createMap("fileName", fileName,
                                "fileUploadPath", filePath,
                                "filePath", fileUri));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return Result.error(BizExceptionEnum.FILE_FORMAT_INCORRECT);
        }
    }
}
